package dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import util.DBUtil;
import dao.ComputerDAO;
import entity.Computer;

public class ComputerDAOJdbcImpl implements ComputerDAO {

	public List<Computer> findAll() throws Exception {
		List<Computer> computers = new ArrayList<Computer>();
		Connection conn = DBUtil.getConnection();
		PreparedStatement prep = 
			conn.prepareStatement("select * from t_computer2");
		ResultSet rst = prep.executeQuery();
		while(rst.next()){
			String model = rst.getString("model");
			String picName = rst.getString("picName");
			String prodDesc = rst.getString("prodDesc");
			double price = rst.getDouble("price");
			long id = rst.getLong("id");
			Computer c = new Computer(model,picName,prodDesc,price);
			c.setId(id);
			computers.add(c);
		}
		DBUtil.close(conn);
		return computers;
	}

	public Computer findById(long id) throws Exception {
		Computer c = null;
		Connection conn = DBUtil.getConnection();
		PreparedStatement prep = 
			conn.prepareStatement("select * from t_computer2 where id=?");
		prep.setLong(1, id);
		ResultSet rst = prep.executeQuery();
		if(rst.next()){
			String model = rst.getString("model");
			String picName = rst.getString("picName");
			String prodDesc = rst.getString("prodDesc");
			double price = rst.getDouble("price");
			c = new Computer(model,picName,prodDesc,price);
			c.setId(id);
		}
		DBUtil.close(conn);
		return c;
	}

	public void save(Computer c) throws Exception {
		Connection conn = DBUtil.getConnection();
		PreparedStatement prep = 
			conn.prepareStatement("insert into t_computer2(model,picName,prodDesc,price) values(?,?,?,?)");
		prep.setString(1, c.getModel());
		prep.setString(2, c.getPicName());
		prep.setString(3, c.getProdDesc());
		prep.setDouble(4,c.getPrice());
		prep.executeUpdate();
		DBUtil.close(conn);

	}

}
